package cc.chengheng.security.springmvc.controller;

import cc.chengheng.security.springmvc.model.AuthenticationRequest;
import cc.chengheng.security.springmvc.model.UserDto;
import cc.chengheng.security.springmvc.service.IAuthenticationService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@RestController
public class LoginController {

    @Resource
    IAuthenticationService authenticationService;

    @RequestMapping(value = "/login", produces = {"text/plain; charset=utf-8;"})
    public String login(AuthenticationRequest authenticationRequest, HttpSession session) {

        UserDto userDto = authenticationService.authentication(authenticationRequest);

        session.setAttribute(UserDto.SESSION_USER_KEY, userDto);

        return userDto.getUsername() + "登录成功";
    }

    @RequestMapping(value = "/logout", method = {RequestMethod.GET}, produces = {"text/plain; charset=utf-8;"})
    public String logout(HttpSession session){
        session.invalidate();
        return "退出成功";
    }


    @RequestMapping(value = "/p1", method = {RequestMethod.GET}, produces = {"text/plain; charset=utf-8;"})
    public String p1(HttpSession session){
        String fullName = null;

        Object userObj = session.getAttribute(UserDto.SESSION_USER_KEY);
        if(userObj != null){
            fullName = ((UserDto)userObj).getFullName();
        }else{
            fullName = "匿名";
        }
        return fullName + " 访问资源1";
    }

    @RequestMapping(value = "/p2", method = {RequestMethod.GET}, produces = {"text/plain; charset=utf-8;"})
    public String p2(HttpSession session){
        String fullName = null;

        Object userObj = session.getAttribute(UserDto.SESSION_USER_KEY);
        if(userObj != null){
            fullName = ((UserDto)userObj).getFullName();
        }else{
            fullName = "匿名";
        }
        return fullName + " 访问资源1";
    }
}
